<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 搜索关键词
const searchKeyword = ref('')
// 搜索历史
const searchHistory = ref([
  '动画新番',
  '音乐推荐',
  '游戏攻略'
])
// 热门搜索
const hotSearches = ref([
  { keyword: '2024年度动画盘点', rank: 1 },
  { keyword: '流行歌曲排行榜', rank: 2 },
  { keyword: '热门游戏测评', rank: 3 },
  { keyword: '科技新品发布会', rank: 4 },
  { keyword: '美食制作教程', rank: 5 }
])
// 搜索结果
const searchResults = ref([])
// 是否显示搜索结果
const showResults = ref(false)
// 加载状态
const isLoading = ref(false)
// 当前页码
const currentPage = ref(1)
// 每页显示数量
const pageSize = 20
// 总页数
const totalPages = ref(0)

// 模拟搜索结果数据
const mockVideos = [
  {
    id: 1,
    title: '【动画】2024年度动画盘点：最值得期待的十部新番',
    cover: 'https://picsum.photos/id/10/400/225',
    uploader: '动漫资讯站',
    views: '12.5万',
    likes: '8932',
    duration: '15:23',
    uploadDate: '2024-01-10'
  },
  {
    id: 2,
    title: '【音乐】2024流行歌曲排行榜TOP50',
    cover: 'https://picsum.photos/id/11/400/225',
    uploader: '音乐频道',
    views: '25.3万',
    likes: '15678',
    duration: '30:45',
    uploadDate: '2024-01-08'
  },
  {
    id: 3,
    title: '【游戏】热门游戏最新版本详细测评',
    cover: 'https://picsum.photos/id/12/400/225',
    uploader: '游戏玩家',
    views: '18.7万',
    likes: '12345',
    duration: '20:18',
    uploadDate: '2024-01-05'
  },
  {
    id: 4,
    title: '【科技】最新科技产品发布会全程直播',
    cover: 'https://picsum.photos/id/13/400/225',
    uploader: '科技前沿',
    views: '32.1万',
    likes: '23456',
    duration: '45:36',
    uploadDate: '2024-01-03'
  },
  {
    id: 5,
    title: '【美食】简单易学的家常菜制作教程合集',
    cover: 'https://picsum.photos/id/14/400/225',
    uploader: '美食达人',
    views: '15.6万',
    likes: '9876',
    duration: '25:42',
    uploadDate: '2024-01-01'
  },
  {
    id: 6,
    title: '【动画】经典动画重温：那些年我们追过的神作',
    cover: 'https://picsum.photos/id/15/400/225',
    uploader: '动画研究社',
    views: '9.8万',
    likes: '7654',
    duration: '22:15',
    uploadDate: '2023-12-28'
  }
]

// 监听URL参数变化
onMounted(() => {
  const keyword = route.query.keyword
  if (keyword) {
    searchKeyword.value = keyword
    performSearch(keyword)
  }
})

// 执行搜索
const performSearch = (keyword) => {
  if (!keyword.trim()) return
  
  isLoading.value = true
  showResults.value = true
  
  // 模拟搜索请求延迟
  setTimeout(() => {
    // 过滤模拟数据作为搜索结果
    const filteredResults = mockVideos.filter(video => 
      video.title.toLowerCase().includes(keyword.toLowerCase()) ||
      video.uploader.toLowerCase().includes(keyword.toLowerCase())
    )
    
    // 添加分页逻辑
    totalPages.value = Math.ceil(filteredResults.length / pageSize)
    searchResults.value = filteredResults.slice(0, pageSize)
    currentPage.value = 1
    
    // 添加到搜索历史（如果不存在）
    if (!searchHistory.value.includes(keyword)) {
      searchHistory.value.unshift(keyword)
      // 限制历史记录数量
      if (searchHistory.value.length > 10) {
        searchHistory.value.pop()
      }
    }
    
    isLoading.value = false
  }, 800)
}

// 搜索提交
const handleSearch = (event) => {
  event.preventDefault()
  if (searchKeyword.value.trim()) {
    // 更新URL参数
    router.push({ path: '/search', query: { keyword: searchKeyword.value } })
    performSearch(searchKeyword.value)
  }
}

// 点击历史记录或热门搜索
const searchFromHistory = (keyword) => {
  searchKeyword.value = keyword
  router.push({ path: '/search', query: { keyword } })
  performSearch(keyword)
}

// 清除搜索历史
const clearHistory = () => {
  searchHistory.value = []
}

// 导航到视频详情
const goToVideo = (videoId) => {
  router.push(`/video/${videoId}`)
}

// 页码变化
const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return
  
  currentPage.value = page
  isLoading.value = true
  
  // 模拟分页加载
  setTimeout(() => {
    const start = (page - 1) * pageSize
    const end = start + pageSize
    
    const filteredResults = mockVideos.filter(video => 
      video.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      video.uploader.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
    
    searchResults.value = filteredResults.slice(start, end)
    isLoading.value = false
  }, 500)
}

// 格式化数字
const formatNumber = (num) => {
  if (typeof num === 'string' && num.includes('万')) {
    return num
  }
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}
</script>

<template>
  <div class="search-container">
    <div class="search-header">
      <form class="search-form" @submit="handleSearch">
        <div class="search-input-wrapper">
          <input 
            v-model="searchKeyword" 
            type="text" 
            class="search-input"
            placeholder="搜索视频、用户或标签"
            autofocus
          />
          <button type="submit" class="search-button">
            <span class="search-icon">🔍</span>
          </button>
        </div>
      </form>
    </div>

    <!-- 搜索结果区域 -->
    <div v-if="showResults" class="search-results-container">
      <div class="search-results-header">
        <div class="search-summary">
          <span class="search-keyword">{{ searchKeyword }}</span>
          <span class="result-count">的搜索结果</span>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <div class="loading-spinner"></div>
        <div class="loading-text">正在搜索中...</div>
      </div>

      <!-- 搜索结果为空 -->
      <div v-else-if="searchResults.length === 0" class="no-results">
        <div class="no-results-icon">🤔</div>
        <div class="no-results-text">没有找到与 "{{ searchKeyword }}" 相关的内容</div>
        <div class="no-results-hint">试试其他关键词或查看热门搜索</div>
      </div>

      <!-- 搜索结果列表 -->
      <div v-else class="search-results">
        <div 
          v-for="video in searchResults" 
          :key="video.id" 
          class="search-result-item"
          @click="goToVideo(video.id)"
        >
          <div class="video-thumbnail">
            <img :src="video.cover" :alt="video.title" class="thumbnail-img" />
            <div class="video-duration">{{ video.duration }}</div>
          </div>
          <div class="video-info">
            <div class="video-title">{{ video.title }}</div>
            <div class="video-stats">
              <span class="stat-item">{{ formatNumber(video.views) }}次播放</span>
              <span class="stat-item">{{ formatNumber(video.likes) }}点赞</span>
              <span class="stat-item">{{ video.uploadDate }}</span>
            </div>
            <div class="uploader-info">
              <img 
                :src="`https://picsum.photos/id/${video.id + 30}/100/100`" 
                :alt="video.uploader" 
                class="uploader-avatar" 
              />
              <span class="uploader-name">{{ video.uploader }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页控件 -->
      <div v-if="totalPages > 1 && !isLoading" class="pagination">
        <button 
          class="page-button" 
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
        >
          上一页
        </button>
        <div class="page-numbers">
          <span 
            v-for="page in totalPages" 
            :key="page"
            class="page-number"
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
          >
            {{ page }}
          </span>
        </div>
        <button 
          class="page-button" 
          :disabled="currentPage === totalPages"
          @click="changePage(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 搜索前的推荐内容 -->
    <div v-else class="search-recommendations">
      <!-- 搜索历史 -->
      <div v-if="searchHistory.length > 0" class="search-history">
        <div class="section-header">
          <h3 class="section-title">搜索历史</h3>
          <button class="clear-history" @click="clearHistory">
            <span class="clear-icon">🗑️</span>
            <span class="clear-text">清空</span>
          </button>
        </div>
        <div class="history-tags">
          <span 
            v-for="(keyword, index) in searchHistory" 
            :key="index"
            class="history-tag"
            @click="searchFromHistory(keyword)"
          >
            {{ keyword }}
          </span>
        </div>
      </div>

      <!-- 热门搜索 -->
      <div class="hot-searches">
        <h3 class="section-title">热门搜索</h3>
        <div class="hot-search-list">
          <div 
            v-for="item in hotSearches" 
            :key="item.rank"
            class="hot-search-item"
            @click="searchFromHistory(item.keyword)"
          >
            <span class="search-rank" :class="{ top: item.rank <= 3 }">
              {{ item.rank }}
            </span>
            <span class="search-keyword">{{ item.keyword }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-container {
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
}

/* 搜索栏 */
.search-header {
  margin-bottom: 32px;
}

.search-form {
  display: flex;
  justify-content: center;
}

.search-input-wrapper {
  position: relative;
  width: 100%;
  max-width: 600px;
}

.search-input {
  width: 100%;
  padding: 14px 20px;
  padding-right: 56px;
  font-size: 16px;
  border: 1px solid var(--border-color);
  border-radius: 28px;
  outline: none;
  transition: all 0.3s ease;
  background-color: var(--white);
  color: var(--text-primary);
}

.search-input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(251, 114, 153, 0.1);
}

.search-button {
  position: absolute;
  right: 4px;
  top: 50%;
  transform: translateY(-50%);
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 50%;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.search-button:hover {
  background-color: #e06491;
}

.search-icon {
  font-size: 18px;
}

/* 搜索推荐内容 */
.search-recommendations {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 32px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

/* 搜索历史 */
.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.history-tag {
  padding: 8px 16px;
  background-color: var(--white);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  font-size: 14px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.3s ease;
}

.history-tag:hover {
  background-color: var(--hover-background);
  color: var(--primary-color);
  border-color: var(--primary-color);
}

.clear-history {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: var(--text-light);
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.clear-history:hover {
  color: var(--text-secondary);
}

.clear-icon {
  font-size: 14px;
}

/* 热门搜索 */
.hot-search-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.hot-search-item {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.hot-search-item:hover {
  background-color: var(--hover-background);
}

.search-rank {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-secondary);
  background-color: var(--hover-background);
  border-radius: 4px;
}

.search-rank.top {
  background-color: var(--primary-color);
  color: white;
}

.search-keyword {
  color: var(--text-primary);
  font-size: 14px;
}

/* 搜索结果区域 */
.search-results-header {
  margin-bottom: 20px;
}

.search-summary {
  font-size: 16px;
  color: var(--text-secondary);
}

.search-keyword {
  color: var(--primary-color);
  font-weight: 600;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  gap: 16px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--border-color);
  border-top: 3px solid var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: var(--text-secondary);
  font-size: 16px;
}

/* 无结果状态 */
.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  gap: 16px;
}

.no-results-icon {
  font-size: 48px;
}

.no-results-text {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-primary);
}

.no-results-hint {
  font-size: 14px;
  color: var(--text-light);
}

/* 搜索结果列表 */
.search-results {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-result-item {
  display: flex;
  gap: 16px;
  background-color: var(--white);
  border-radius: var(--border-radius);
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-sm);
}

.search-result-item:hover {
  background-color: var(--hover-background);
  box-shadow: var(--shadow-md);
}

.video-thumbnail {
  width: 200px;
  aspect-ratio: 16/9;
  position: relative;
  flex-shrink: 0;
}

.thumbnail-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.video-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.video-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 8px;
  line-height: 1.4;
}

.video-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
}

.stat-item {
  font-size: 13px;
  color: var(--text-light);
}

.uploader-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.uploader-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
}

.uploader-name {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 分页控件 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 40px;
}

.page-button {
  padding: 8px 16px;
  background-color: var(--white);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-button:hover:not(:disabled) {
  background-color: var(--hover-background);
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.page-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 8px;
}

.page-number {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-number:hover {
  background-color: var(--hover-background);
  color: var(--primary-color);
}

.page-number.active {
  background-color: var(--primary-color);
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-recommendations {
    grid-template-columns: 1fr;
    gap: 24px;
  }
  
  .search-result-item {
    flex-direction: column;
  }
  
  .video-thumbnail {
    width: 100%;
  }
  
  .search-container {
    padding: 0 16px;
    margin: 20px auto;
  }
  
  .search-header {
    margin-bottom: 20px;
  }
  
  .video-stats {
    flex-wrap: wrap;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .search-input {
    font-size: 14px;
    padding: 12px 16px;
    padding-right: 48px;
  }
  
  .search-button {
    width: 36px;
    height: 36px;
  }
  
  .search-icon {
    font-size: 16px;
  }
  
  .pagination {
    gap: 8px;
  }
  
  .page-button {
    padding: 6px 12px;
    font-size: 14px;
  }
  
  .page-number {
    width: 28px;
    height: 28px;
    font-size: 14px;
  }
  
  .section-title {
    font-size: 16px;
  }
}
</style>